<template>
  <div id="FaceAuthenAndiord">
    <!-- 人脸的图片 -->
    <canvas id="canvas" width="200px" height="200px" v-show="false"></canvas>
    <div v-if="kk == '0'">
      <div class="di">
        <div class="one">人脸认证</div>
        <div class="two">请衣着平整，平视屏幕，并正对光源</div>
      </div>
      <div class="tip">
        <div>
          <img src="../../assets/icons/online/yj.png" alt="">
          <span>不能佩戴眼镜</span>
        </div>
        <div>
          <img src="../../assets/icons/online/zl.png" alt="">
          <span>不能遮挡脸部</span>
        </div>
        <div>
          <img src="../../assets/icons/online/yt.png" alt="">
          <span>不能仰头俯拍</span>
        </div>
      </div>
      <div class="start" @click="next">开始拍摄</div>
    </div>
    
    <!-- 录制中的部分 -->
    <div v-if="kk == '1'" class="imgFather">
      <!-- <div class="videoOn" v-if="kk == '1'" id="sure" ref="sure">● 录制中</div> -->
      <div class="img_borther">
        <p class="oneP">请保持{{currentSecond}}秒钟</p>
        <video id="video" autoplay ref="capture" class="video0"></video>
      </div>
    </div>
    <!-- 弹出框提示 -->
    <van-overlay :show="show">
      <div class="wrapper" @click.stop>
        <div class="block">
          <div class="show" v-show="decide == true">
            <p class="oneP">请牢记一下动作</p>
            <p>
              此提示将于<span class="number">{{ number }}</span
              >后过期
            </p>
            <p>此次视频时长<span class="number">3-8</span>秒最佳哦~</p>
            <div class="daddy">
              <h3>
                <span class="sp1" v-if="action == 3">点点头</span>
                <span class="sp1" v-if="action == 4">张张嘴</span>
              </h3>
            </div>
            <!-- 假如是IOS端 -->
            <div class="father" v-show="kl == '0'">
              <label for="videoInput1">
                <!-- <input
                  type="file"
                  id="videoInput1"
                  accept="video/*"
                  capture="user"
                  @change="submit($event)"
                  hidden
                  ref="videoInput1"
                /> -->
                <span class="btn" v-if="start === 0" @click="goImg">记住了，开始录制</span>
              </label>
              <van-button disabled type="info" v-if="start > 0" class="btn3"
                >记住了，开始录制 <span v-if="goStart">({{ start }}秒)</span></van-button
              >
            </div>
            <!-- <input
              type="file"
              id="videoInput2"
              accept="video/*"
              capture="user"
              @change="submit($event)"
              hidden
              ref="videoInput2"
            /> -->
            <!-- 假如是安卓端 -->
            <div v-show="kl == '1'">
              <span class="btn" v-if="start === 0" @click="goImg">记住了，开始录制</span>
              <!-- <button class="btn" v-if="start === 0" @click="goImg">记住了，开始录制</button> -->
              <van-button disabled type="info" v-if="start > 0" class="btn3"
                >记住了，开始录制 <span v-if="goStart">({{ start }}秒)</span></van-button
              >
            </div>
          </div>
          <!-- 不展示 -->
          <div class="showOf" v-show="decide2 == true">
            <img src="../../assets/icons/online/fail.png" alt="" class="fail" />
            <p class="shibai">获取动作失败</p>
            <p class="dongzuo">请重新获取动作</p>
            <button class="btn2" @click="goJiekou">重新获取</button>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Dialog, Overlay, Toast, Button } from 'vant';
import Header from '../../components/Header.vue';
import { cloudApi } from '@/api/indexApi';
import lrz from "lrz";
import { VanImagePreview } from 'node_modules/vant/types/image-preview';
@Component({
  components: {
    [Button.name]: Button,
    [Overlay.name]: Overlay,
    [Dialog.Component.name]: Dialog.Component,
    Header,
  },
})
export default class ProductList extends Vue {
  public show: boolean = false;
  public number: number = 60;
  public action: any = '';
  public start: any = 3;
  public arr: any = [];
  public decide: any = '2';
  public goStart: boolean = true;
  public time: any = '';
  public time2: any = '';
  public decide2: any = false;
  public time3: any = '';
  public time4: any = '';
  public time5: any = '';
  public time6: any = '';
  public v: number = 0;
  public kk: any = '0';
  public video: any = '';
  public file: any = '';
  public kl: any = '0';
  public currentSecond: any = 3;
  public userData:any = "";
  public routeString:any = "";
  public picture:any = "";
  created() {
    document.title = '人脸识别'
    this.userData = sessionStorage.getItem('faceParmas');
    this.userData = JSON.parse(this.userData);
    this.routeString = this.$route.query.route;
    this.arr = { action: '' };
    // 判断ios或者安卓
    var u = navigator.userAgent,
      app = navigator.appVersion;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isiOS == true) {
      this.kl = '0';
    } else if (isAndroid == true) {
      if (this.hasGetUserMedia()) {
        this.kl = '1';
      } else {
        this.kl = '0';
      }
    }
  }
  hasGetUserMedia() {
    return !!(
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia
    );
  }
  mounted() {
    var getUserMedia =
      navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    if (window.history && window.history.pushState) {
      history.pushState(null, document.URL);
      window.addEventListener('popstate', this.goBack, false);
    }
  }
  goImg() {
    // 清除之前页面的所有计时器
    clearInterval(this.time);
    clearInterval(this.time2);
    this.kk = '1';
    this.show = false;
    let that = this;
    navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia ||
      window.getUserMedia;
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: { facingMode: 'user' ,width: 200, height: 200}, //调用前置摄像头，后置摄像头使用video: { facingMode: { exact: "environment" } }
        })
        .then(function(mediaStream) {
          that.getVideoStream(mediaStream);
        })
        .catch(function(error) {
          that.getFail(error);
        });
    } else if (navigator.getUserMedia) {
      navigator.getUserMedia(
        { video: { facingMode: 'user' ,width: 200, height: 200}, audio: false },
        function onSuccess(mediaStream) {
          console.log('已点击允许,开启成功');
          that.getVideoStream(mediaStream);
        },
        function onError(error) {
          that.getFail(error);
        },
      );
    } else {
      that.$toast('请检查您的摄像头访问权限是否关闭！');
    }
  }
  //调用成功
  getVideoStream(stream) {
    const vm = this;
    let buffer = stream;
    let oCapture = this.$refs.capture;
    if (oCapture.mozSrcObject !== undefined) {
      oCapture.mozSrcObject = buffer;
    } else {
      try {
        oCapture.srcObject = buffer;
      } catch (error) {
        const vendorURL = window.URL || window.webkitURL;
        oCapture.src = vendorURL && vendorURL.createObjectURL(buffer);
      }
    }
    oCapture.onloadedmetadata = () => {
      console.log('开始录制');
      oCapture.play();
      vm.videoStream(stream);
    };
  }
  videoStream(stream) {
    const vm = this;
    let mediaRecorder = new MediaRecorder(stream);
    //大于最长时间则停止录制, 回调数据
    mediaRecorder.ondataavailable = function(e) {
      stream && stream.getTracks() && stream.getTracks().length && stream.getTracks()[0].stop();
      let parmas = {
        username:vm.userData.username,//用户名 "刘正"||
        idCard:vm.userData.idCard,//身份证号 "220382199309170634"||
        cardType:vm.userData.cardType,//证件类型 "01"||
        userId:vm.userData.userId,//"5581"||
        phone:vm.userData.mobile,//"18310674957"||
        openId:vm.userData.openId, //"oIZvj6Ix38qkx9G2bR0eUqhvlTAM"||
        picture:vm.picture,
      }
      vm.picture = "";
      cloudApi.face(parmas).then(res=>{
        if(res.data.header.statusCode == "00000000"){
          if(res.data.body.status == "1"){
            let params ={
              idCard:vm.userData.idCard,
              mobile:vm.userData.mobile,
              idType:vm.userData.cardType,
              name:vm.userData.username,
              userId:vm.userData.userId,
              sex:""
            }
            cloudApi.peaceOfMind(params).then(data=>{})
            if(vm.routeString){
              let route:any = JSON.parse(vm.routeString)
              vm.$router.push(route)
            }else if(sessionStorage.getItem('sourceUrl')){
              let htmlUrl:any =sessionStorage.getItem('sourceUrl')
              wx.miniProgram.redirectTo({ 
                  url: '/pages/webview/webview?url='+encodeURIComponent(htmlUrl)+'&flag=1'
              }); 
            }else{
              vm.$router.push({path:"personalCard"})
            }
          }else{
            Dialog.alert({ title: '温馨提示', message: res.data.body.msg+",剩余验证"+ res.data.body.num+"次"})
          }
        }else{
          Dialog.alert({ title: '温馨提示', message: res.data.header.message})
        }
      })
    };

    mediaRecorder.start(60000); //五秒后取数据
    this.currentSecond = 3;
    let timer = setInterval(() => {
      this.currentSecond--;
      if (this.currentSecond < 1) {
        var video = document.getElementById("video");
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(video, 0, 0, 200, 200);
        this.lrzImg(canvas.toDataURL("image/png"),mediaRecorder);
        // mediaRecorder.stop();
        vm.kk = '0';
        clearInterval(timer);
      }
    }, 1000);
  }
  lrzImg(file:any,mediaRecorder:any){
    let _that = this;
    lrz(file,{ quality: 0.7 }).then(function(res:any){
      if(res.fileLen>32*1024){
        _that.lrzImg(res.base64,mediaRecorder)
      }else{
        _that.picture = res.base64.split(";base64,")[1];
        mediaRecorder.stop();
      }
    })
  }
  //打开摄像头失败
  getFail(error) {
    let that = this;
    that.kk = '0';
    clearInterval(that.time5);
    this.kl = '0';
    let jk = document.getElementById('videoInput2');
    // console.log('1231',jk);
    jk.click();
    // this.$toast(error ? error.toString() : "您的设备不支持摄像头调用");
    console.log(error ? error.toString() : '凉凉');
  }
  // 点击开始拍摄
  next() {
    let that = this;
    this.goImg();
    // that.show = true;
    // if (that.show == true) {
    //   that.decide = true;
    //   // 生成人脸的随机action
    //   var min = 3;
    //   var max = 4;
    //   var rand = Math.floor(Math.random() * (max - min + 1)) + min;
    //   that.action = rand;
    //   that.start = 3;
    //   that.number = 60;
    //   that.goStart = true;
    //   // 三秒倒计时
    //   that.time = setInterval(() => {
    //     that.start--;
    //     if (that.start == 0) {
    //       clearInterval(that.time);
    //       that.goStart = false;
    //     }
    //   }, 1000);
    //   // 60秒倒计时
    //   that.time2 = setInterval(() => {
    //     that.number--;
    //     if (that.number == 0) {
    //       clearInterval(that.time2);
    //       that.decide = false;
    //       that.decide2 = true;
    //     } else {
    //       that.decide = true;
    //       that.decide2 = false;
    //     }
    //   }, 1000);
    // }
  }
  // 点击重新获取
  goJiekou() {
    let that = this;
    that.decide = true;
    that.decide2 = false;
    that.number = 60;
    that.start = 3;
    that.goStart = true;
    var min = 3;
    var max = 4;
    var rand = Math.floor(Math.random() * (max - min + 1)) + min;
    that.action = rand;
    that.time3 = setInterval(() => {
      that.number--;
      if (that.number == 0) {
        clearInterval(that.time3);
        that.decide = false;
        that.decide2 = true;
      } else {
        that.decide = true;
        that.decide2 = false;
      }
    }, 1000);
    // 按钮倒计时
    that.time4 = setInterval(() => {
      that.start--;
      if (that.start == 0) {
        clearInterval(that.time4);
        that.goStart = false;
      }
    }, 1000);
  }
  // 页面销毁，清除所有计时器
  beforeDestroy() {
    console.log('beforeDestroy');
    clearInterval(this.time5);
    clearInterval(this.time);
    clearInterval(this.time2);
    clearInterval(this.time3);
    clearInterval(this.time4);
    clearInterval(this.time6);
  }
  //
  destroyed() {
    window.removeEventListener('popstate', this.goBack, false);
  }
  goBack() {
    //指定返回路径
    if(sessionStorage.getItem('sourceBack')=='xiaochengxu'){
      sessionStorage.removeItem('sourceBack')
      if((window as any).wx.miniProgram){
        (window as any).wx.miniProgram.navigateBack({
          delta: history.length
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
@height: 100%;
#FaceAuthenAndiord {
  width: 100vw;
  height: 100vh;
  background: white;
  text-align: center;
  box-sizing: border-box;
  .di{
    width: 100vw;
    height: 62vh;
    background: url(../../assets/icons/online/di.png) no-repeat;
    background-size: 100% 100%;
  }
  .currentSecond {
    background: white;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    height: 45px;
    font-size: 16px;
    line-height: 45px;
    text-align: center;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    color: red;
  }
  .img_borther {
    // box-shadow: ;
    background: white;
    border-radius: 10px;
    box-sizing: border-box;
    box-shadow: 5px 0px 5px -5px #e7e7e7, -5px 0px 5px -5px #e7e7e7;
    width: 80%;
    height: 300px;
    position: absolute;
    left: 10%;
    top: 10%;
    .video0 {
      width: 200px;
      height: 200px;
      position: absolute;
      left: 0;
      bottom: 0;
      right: 0;
      top: 40px;
      margin: auto;
      border-radius: 50%;
    }
    p{
      color: #333333;
      margin-top: 30px;
      font-size: 18px;
    }
  }
  
  .face1 {
    width: 100%;
    height: 100%;
  }
  .imgFather {
    background: rgba(0, 0, 0, 0.5);
    width: 100vw;
    height: 100vh;
    padding: 0;
    position: relative;
    display: flex;
  }
  .videoOn {
    color: red;
    font-size: 20px;
    position: absolute;
    top: 2%;
    left: 40%;
    z-index: 1000;
  }
  .showVideo {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0px;
    bottom: 0;
  }
  .wrapper {
    width: 100%;
    text-align: center;
    height: 100%;
    box-sizing: border-box;
    .daddy {
      width: 100%;
      box-sizing: border-box;
      border-radius: 5px;
      font-weight: bold;
      color: black;
      .sp1 {
        display: inline-block;
        width: 100%;
        height: 50px;
        margin: 0 auto;
        letter-spacing: 2;
        text-align: center;
        border-radius: 5px;
      }
    }
    .showOf {
      padding: 10% 0;
      width: 100%;
      .fail {
        width: 40px;
        height: 35px;
      }
      P{
        margin-bottom: 10px;
      }
      .btn2 {
        width: 90%;
        height: 45px;
        background: #d80c24;
        font-size: 18px;
        border: none;
        color: white;
        position: absolute;
        bottom: 5%;
        left: 5%;
        border-radius: 10px;
      }
      .shibai {
        font-size: 18px;
        color: black;
      }
      .dongzuo {
        font-size: 14px;
        color: #999999;
      }
    }
    .number {
      color: red;
    }
    .camera-input {
      width: 200px;
    }
    .btn {
      width: 90%;
      border-radius: 10px;
      height: 45px;
      background: #d80c24;
      color: white;
      font-size: 18px;
      line-height: 45px;
      position: absolute;
      bottom: 5%;
      left: 5%;
    }
    .btn3 {
      width: 90%;
      border-radius: 10px;
      height: 45px;
      background: #d80c24;
      color: white;
      font-size: 16px;
      line-height: 45px;
      position: absolute;
      bottom: 5%;
      left: 5%;
      border: none;
    }
    .show {
      width: 100%;
      box-sizing: border-box;
      font-size: 16px;
      color: #999999;
      .oneP {
        font-size: 18px;
        color: black;
      }
      p{
        margin-bottom: 10px;
      }
    }
    .xx {
      width: 50px;
      height: 50px;
    }
  }
  .block {
    border-radius: 10px;
    background: white;
    width: 65%;
    height: 40%;
    box-sizing: border-box;
    padding: 20px 20px;
    margin: 0 auto;
    margin-top: 40%;
    margin-bottom: 20px;
    position: relative;
  }
  .one {
    font-size: 24px;
    box-sizing: border-box;
    padding: 35px 0 25px 0;
    color: #fff;
    font-weight: 500;
  }
  .two {
    font-size: 16px;
    color: #fff;
    font-weight: 500;
  }
  .start {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 85px;
    background: url(../../assets/icons/online/btn.png) no-repeat;
    background-size: 100% 100%;
    color: #fff;
    font-weight: 400;
    font-size: 18px;
    padding: 20px;
    box-sizing: border-box;
  }
  .tip{
    display: flex;
    justify-content: space-around;
    padding-top: 25px;
    div{
      width: 33vw;
      text-align: center;
      span{
        color: #3EA07B;
        font-size: 16px;
        font-weight: 400;
      }
      img{
        width: 50px;
        height: 50px;
        display: block;
        margin-left: 50%;
        transform: translateX(-25px);
        margin-bottom: 15px;
      }
    }
  }
}
</style>
